package com.zzyl.framework.interceptor;

import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户端请求拦截器
 *
 * @Author katana
 * @Date 2025/5/23 17:57
 */
@Component
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;
    
    /**
     * 访问拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果不是controller资源，直接放行
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        
        //获取请求头的token
        String token = request.getHeader("authorization");
        
        //如果为空，响应401
        if(StringUtils.isBlank(token)) {
            response.setStatus(HttpStatus.UNAUTHORIZED);
            throw new BaseException("登录认证失败，401");
        }
        
        //解析Token
        try {
            Claims claims = tokenService.parseToken(token);
            
            //解析成功，设置到ThreadLocal
            Long userId = Long.valueOf(claims.get("userId").toString());
            UserThreadLocal.set(userId);
        } catch (Exception e) {
            e.printStackTrace();
            //解析失败，响应401
            response.setStatus(HttpStatus.UNAUTHORIZED);
            throw new BaseException("登录认证失败，401");
        }
        
        //放行请求
        return true;
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
